//
//  HomeViewController.m
//  huashiedu
//
//  Created by oceans on 2018/7/30.
//  Copyright © 2018年 hema. All rights reserved.
//

#import "HomeViewController.h"
#import "HomeNormalCollectionCell.h"
#import "HomeHeadCollectionCell.h"
#import "HomeHeaderCollectionReusableView.h"
#import "HomeItemCollectionViewCell.h"
#import "HomeItemModel.h"
#import "HomeCollectionCellBaseModel.h"
#import "HomeCollectionScrollHeaderView.h"
#import "HomeRecommendModel.h"
#import "HomeRecommendCollectionCell.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "HttpRequest.h"
#import "HomeImagesModel.h"
#import "HomeDataModel.h"
#import "LocationView.h"
#import "LocationModel.h"
#import "JFCityViewController.h"
#import "ClassListViewController.h"
#import "SchoolListViewController.h"
#import "TeacherListViewController.h"
#import "NormalWebViewController.h"
#import "OAuthAPI.h"
#import "SearchListViewController.h"

@interface HomeViewController () <UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, LocationViewDelegate, HomeHeaderCollectionReusViewDelegate, UITextFieldDelegate, HomeCollectionScrollHeaderDelegate>

@property (strong, nonatomic) UICollectionView *collection;
@property (strong, nonatomic) NSMutableArray <HomeDataModel *> *dataArr;
@property (strong, nonatomic) NSArray <HomeImagesModel *> *scrollImages;
@property (strong, nonatomic) NSArray *imagesUrls;
@property (strong, nonatomic) NSArray <HomeItemModel *> *items;
@property (strong, nonatomic) NSArray <HomeRecommendModel *> *recommends;
@property (strong, nonatomic) LocationView *locationView;

@property (strong, nonatomic) UIView *searchView;
@end

@implementation HomeViewController

- (instancetype)init {
    self = [super init];
    if (self) {
        if ([OAuthAPI getAccessToken].length == 0) {
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadData) name:@"access_token_refresh" object:nil];
        }
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadDataAfterChangeArea) name:locationModelChangedNotification object:nil];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    if ([OAuthAPI getAccessToken].length > 0) {
        [self loadData];
    }
    [self setupView];
}

- (void)loadData {
    
    self.dataArr = [NSMutableArray array];
    self.items = [HomeItemModel items];
    
    [HttpRequest getURL:ksplash paras:nil showProgress:NO successful:^(id  _Nullable result) {
        NSString *url = result[@"data"];
        [[NSUserDefaults standardUserDefaults] setObject:url forKey:@"splash_url"];
    } failed:nil];
    
    __weak typeof(self) weakself = self;
    [HttpRequest getURL:kget_home_header_data paras:nil showProgress:NO successful:^(id  _Nullable result) {
        NSArray *images = [[result objectForKey:@"data"] objectForKey:@"broadcast"];
        NSMutableArray *mimages = [NSMutableArray arrayWithCapacity:images.count];
        NSMutableArray *urls = [NSMutableArray arrayWithCapacity:images.count];
        for (NSDictionary *dic in images) {
            HomeImagesModel *model = [[HomeImagesModel alloc] initWithDic:dic];
            [mimages addObject:model];
            [urls addObject:model.thumb];
        }
        weakself.scrollImages = mimages;
        weakself.imagesUrls = urls;
        
        NSArray *recommends = [[result objectForKey:@"data"] objectForKey:@"recommend"];
        NSMutableArray *mrecos = [NSMutableArray arrayWithCapacity:recommends.count];
        for (NSDictionary *dic in recommends) {
            HomeRecommendModel *model = [[HomeRecommendModel alloc] initWithDic:dic];
            [mrecos addObject:model];
        }
        weakself.recommends = mrecos;
        if (weakself.collection != nil) {
            [weakself.collection reloadData];
        }
    } failed:nil];
    
    NSDictionary *para = nil;
    if ([LocationModel shared].areaNumber.length > 0) {
        para = @{@"area": [LocationModel shared].areaNumber};
    }
    [HttpRequest getURL:kget_home_data paras:para showProgress:NO successful:^(id  _Nullable result) {
        NSArray *array = [result objectForKey:@"data"];
        for (NSDictionary *dic in array) {
            HomeDataModel *model = [[HomeDataModel alloc] initWithDic:dic];
            [weakself.dataArr addObject:model];
        }
        if (weakself.collection != nil) {
            [weakself.collection reloadData];
        }
    } failed:nil];
}

/**改变区县位置后刷新*/
- (void)loadDataAfterChangeArea {
    
    [self.dataArr removeAllObjects];
    NSDictionary *para = nil;
    if ([LocationModel shared].areaNumber.length > 0) {
        para = @{@"area": [LocationModel shared].areaNumber};
    }
    __weak typeof(self) weakself = self;
    [HttpRequest getURL:kget_home_data paras:para showProgress:NO successful:^(id  _Nullable result) {
        NSArray *array = [result objectForKey:@"data"];
        for (NSDictionary *dic in array) {
            HomeDataModel *model = [[HomeDataModel alloc] initWithDic:dic];
            [weakself.dataArr addObject:model];
        }
        if (weakself.collection != nil) {
            [weakself.collection reloadData];
        }
    } failed:nil];
}

- (void)locationViewTaped {
    JFCityViewController *controller = [[JFCityViewController alloc] init];
    [self.tabBarController.navigationController presentViewController:controller animated:YES completion:nil];
}

- (void)locationViewWidthChanged {
    self.navigationItem.leftBarButtonItem.width = _locationView.bounds.size.width;
}

- (void)setupNavigation {
    
    self.locationView = [LocationView locationView];
    _locationView.delegate = self;
    _locationView.frame = CGRectMake(0, 0, 70, 44);
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:_locationView];
    item.width = 70;
    self.tabBarController.navigationItem.leftBarButtonItem = item;
    self.tabBarController.navigationItem.titleView = self.searchView;
}

- (UIView *)searchView {
    if (!_searchView) {
        _searchView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth - 20 - _locationView.frame.size.width, 44.0)];
        UITextField *textfield = [[UITextField alloc] initWithFrame:CGRectMake(0, 7, _searchView.bounds.size.width, 30)];
        textfield.backgroundColor = COLOR(235, 236, 237, 1);
        textfield.layer.cornerRadius = 14.0;
        textfield.layer.masksToBounds = YES;
        textfield.font = [UIFont systemFontOfSize:15.0];
        textfield.textAlignment = NSTextAlignmentCenter;
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"  请输入关键词" attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor colorWithRed:179/255.0 green:179/255.0 blue:179/255.0 alpha:1.0]}];
        NSTextAttachment *atta = [[NSTextAttachment alloc] init];
        atta.image = [UIImage imageNamed:@"home_search_icon"];
        atta.bounds = CGRectMake(0, -2, 14, 14);
        [string insertAttributedString:[NSAttributedString attributedStringWithAttachment:atta] atIndex:0];
        textfield.attributedPlaceholder = string;
        textfield.delegate = self;
        [_searchView addSubview:textfield];
    }
    return _searchView;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    
    UINavigationController *con = [SearchListViewController searchController:searchClassClass];
    [self.tabBarController.navigationController presentViewController:con animated:YES completion:nil];
    return NO;
}

- (void)didSelectImageAtIndex:(NSInteger)index {
    
    HomeImagesModel *model = _scrollImages[index];
    NormalWebViewController *controller = [[NormalWebViewController alloc] init];
    controller.url = model.link;
    [self.tabBarController.navigationController pushViewController:controller animated:YES];
}

- (void)setupView {
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setupNavigation];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);
    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, XNavigationHeight, ScreenWidth, ScreenHeight - XNavigationHeight - XTabBarHeight) collectionViewLayout:layout];
    _collection.backgroundColor = [UIColor whiteColor];
    _collection.delegate = self;
    _collection.dataSource = self;
    [_collection registerNib:[UINib nibWithNibName:@"HomeNormalCollectionCell" bundle:nil] forCellWithReuseIdentifier:@"HomeNormalCollectionCell"];
    [_collection registerNib:[UINib nibWithNibName:@"HomeHeadCollectionCell" bundle:nil] forCellWithReuseIdentifier:@"HomeHeadCollectionCell"];
    [_collection registerClass:[HomeHeaderCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HomeHeaderCollectionReusableView"];
    [_collection registerNib:[UINib nibWithNibName:@"HomeItemCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"HomeItemCollectionViewCell"];
    [_collection registerClass:[HomeCollectionScrollHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HomeCollectionScrollHeaderView"];
    [_collection registerClass:[HomeRecommendCollectionCell class] forCellWithReuseIdentifier:@"HomeRecommendCollectionCell"];
    [self.view addSubview:_collection];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setupNavigation];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return _dataArr.count + 2;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    if (section == 0) {
        return UIEdgeInsetsMake(10, 10, 0, 10);
    }else if (section == 1) {
        return UIEdgeInsetsMake(20, 10, 20, 10);
    }
    return UIEdgeInsetsMake(0, 10, 10, 10);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    
    if (section == 0) {
        return CGSizeMake(ScreenWidth, ScreenWidth * 0.396);
    }else if (section == 1) {
        return CGSizeZero;
    }
    return CGSizeMake(ScreenWidth - 20, 60);
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        
        if (indexPath.section == 0) {
            
            HomeCollectionScrollHeaderView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HomeCollectionScrollHeaderView" forIndexPath:indexPath];
            view.delegate = self;
            if (_imagesUrls) {
                view.scrollView.imageURLStringsGroup = _imagesUrls;
            }
            return view;
            
        }else if (indexPath.section == 1) {
            return nil;
        }else {
            
            HomeHeaderCollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HomeHeaderCollectionReusableView" forIndexPath:indexPath];
            view.tag = indexPath.section - 2;
            view.titleLabel.text = _dataArr[indexPath.section - 2].name;
            view.delegate = self;
            return view;
        }
    }
    return nil;
}

- (void)headerViewMoreButtonPressed:(NSInteger)index {
    
    ClassListViewController *controller = [[ClassListViewController alloc] init];
    controller.typeSelect = _dataArr[index]._id;
    [self.tabBarController.navigationController pushViewController:controller animated:YES];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == 0) {
        return 8;
    }else if (section == 1) {
        if (_recommends) {
            return 2;
        }
        return 0;
    }
    return _dataArr[section - 2].recommends.count;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    
    return 15;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    if (section == 0) {
        return (ScreenWidth - 70 * 4 - 20) / 3.0;
    }
    return 11.0;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        return CGSizeMake(70, 70);
    }else if (indexPath.section == 1) {
        return CGSizeMake((ScreenWidth - 31) * 0.5, (ScreenWidth - 31) * 0.275);
    }else {
        
        NSArray <HomeCourseModel*> *array = _dataArr[indexPath.section-2].recommends;
        return array[indexPath.item].size;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        HomeItemCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HomeItemCollectionViewCell" forIndexPath:indexPath];
        cell.imageView.image = [UIImage imageNamed:_items[indexPath.item].image];
        cell.titleLabel.text = _items[indexPath.item].name;
        return cell;
    }else if (indexPath.section == 1) {
        
        HomeRecommendCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HomeRecommendCollectionCell" forIndexPath:indexPath];
        [cell.imageView sd_setImageWithURL:[NSURL URLWithString:_recommends[indexPath.item].thumb]];
        return cell;
    }else {
        
        HomeCourseModel *model = _dataArr[indexPath.section - 2].recommends[indexPath.item];
        if (indexPath.item == 0) {
            
            HomeHeadCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HomeHeadCollectionCell" forIndexPath:indexPath];
            [cell.imageView sd_setImageWithURL:[NSURL URLWithString:model.banner]];
            cell.titleLabel.text = model.title;
            return cell;
        }else {
            
            HomeNormalCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HomeNormalCollectionCell" forIndexPath:indexPath];
            [cell.imageView sd_setImageWithURL:[NSURL URLWithString:model.thumb]];
            cell.titleLabel.text = model.title;
            return cell;
        }
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        ClassListViewController *controller = [[ClassListViewController alloc] init];
        if (_items[indexPath.item]._id == 0) {
            controller.typeSelect = indexPath.item + 1;
        }else {
            controller.typeSelect = _items[indexPath.item]._id;
        }
        [self.tabBarController.navigationController pushViewController:controller animated:YES];
    }else if (indexPath.section == 1) {
        
        if (indexPath.item == 0) {
            
            SchoolListViewController *controller = [[SchoolListViewController alloc] init];
            [self.tabBarController.navigationController pushViewController:controller animated:YES];
        }else {
            
            TeacherListViewController *controller = [[TeacherListViewController alloc] init];
            [self.tabBarController.navigationController pushViewController:controller animated:YES];
        }
    }else {
        
        NormalWebViewController *controller = [[NormalWebViewController alloc] init];
        controller.url = _dataArr[indexPath.section - 2].recommends[indexPath.item].link;
        [self.navigationController pushViewController:controller animated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
